package org.sk.colorfulguild.ui.battle

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import org.sk.colorfulguild.data.BokenshaEntity
import org.sk.colorfulguild.data.TekiEntity
import kotlin.random.Random

class BattleViewModel : ViewModel() {

    private val _text = MutableLiveData<String>().apply {
        value = "This is dashboard Fragment"
    }
    val text: LiveData<String> = _text

    var bokensha = MutableLiveData<BokenshaEntity>()

    var teki = MutableLiveData<TekiEntity>()

    var battleLog = MutableLiveData<String>()

    var battleEnd = false

    init {
        initStatus()
    }

    fun initStatus() {
        battleEnd = false
        BokenshaEntity().apply {
            name = "阿呆"
            hp = 500
            power = Random.nextInt(30, 100)
            def = Random.nextInt(1, 30)
            bokensha.value = this
        }

        TekiEntity().apply {
            name = "阿牛"
            hp = 500
            power = Random.nextInt(30, 100)
            def = Random.nextInt(1, 30)
            teki.value = this
        }
        battleLog.value = "准备战斗"
    }

    fun battle() {
        if (battleEnd) {
            initStatus()
        }
        var bokensha = bokensha.value!!
        var teki = teki.value!!

        var bokenshaDamage = ((0.5 + bokensha.power - teki.def) * (Random.nextDouble(0.95, 1.05))).toInt()
        teki.hp = teki.hp - bokenshaDamage
        battleLog.value = bokensha.name + " 对 " + teki.name + " 造成 " + bokenshaDamage + " 伤害 ;" + teki.name + "剩余HP:" + teki.hp
        this.teki.value = teki

        if (teki.hp < 0) {
            battleEnd = true
            battleLog.value = teki.name + " 阵亡"
            battleLog.value = "===================================================="
            return
        }

        var tekiDamege = ((0.5 + teki.power - bokensha.def) * (Random.nextDouble(0.95, 1.05))).toInt()
        bokensha.hp = bokensha.hp - tekiDamege
        battleLog.value = teki.name + " 对 " + bokensha.name + " 造成 " + tekiDamege + " 伤害 ;" + bokensha.name + "剩余HP:" + bokensha.hp
        this.bokensha.value = bokensha

        if (bokensha.hp < 0) {
            battleEnd = true
            battleLog.value = bokensha.name + " 阵亡"
            battleLog.value = "===================================================="
            return
        }
    }
}